// 财联社电报展示页面JavaScript逻辑 - 调试版本

// 全局变量
let refreshInterval = null;
let currentIntervalTime = 60000; // 默认60秒
let currentWechatConfig = null;
let tempGroups = []; // 临时群组列表

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    console.log('页面加载完成');
    // 初始化页面
    initializePage();
    
    // 绑定事件
    bindEvents();
    
    // 首次加载数据
    loadTelegrams();
    loadStats();
    loadWechatConfig(); // 加载微信配置
    
    // 启动定时刷新
    startAutoRefresh();
});

// 初始化页面
function initializePage() {
    console.log('初始化财联社电报展示页面');
    
    // 初始化微信控制UI
    const wechatToggle = document.getElementById('wechat-toggle');
    if (wechatToggle) {
        wechatToggle.checked = false;
    }
    
    const groupsUl = document.getElementById('groups-ul');
    if (groupsUl) {
        groupsUl.innerHTML = '<li class="no-groups">暂无群组</li>';
    }
}

// 绑定事件
function bindEvents() {
    console.log('开始绑定事件');
    
    // 微信面板折叠/展开按钮
    const wechatPanelToggle = document.getElementById('wechat-panel-toggle');
    if (wechatPanelToggle) {
        wechatPanelToggle.addEventListener('click', function() {
            toggleWechatPanel();
        });
    }
    
    // 微信面板关闭按钮
    const wechatPanelClose = document.getElementById('wechat-panel-close');
    if (wechatPanelClose) {
        wechatPanelClose.addEventListener('click', function() {
            toggleWechatPanel(false);
        });
    }
    
    // 刷新按钮
    const refreshBtn = document.getElementById('refresh-btn');
    console.log('查找刷新按钮:', refreshBtn);
    if (refreshBtn) {
        console.log('找到刷新按钮，绑定点击事件');
        refreshBtn.addEventListener('click', function() {
            console.log('刷新按钮被点击');
            manualRefresh();
        });
    } else {
        console.log('未找到刷新按钮');
    }
    
    // 刷新间隔选择
    const intervalSelect = document.getElementById('refresh-interval');
    if (intervalSelect) {
        intervalSelect.addEventListener('change', function() {
            changeRefreshInterval(this.value);
        });
    }
    
    // 显示数量选择
    const countSelect = document.getElementById('display-count');
    if (countSelect) {
        countSelect.addEventListener('change', function() {
            loadTelegrams();
        });
    }
    
    // 微信推送开关
    const wechatToggle = document.getElementById('wechat-toggle');
    if (wechatToggle) {
        wechatToggle.addEventListener('change', function() {
            handleWechatToggle(this.checked);
        });
    }
    
    // 添加群组按钮
    const addGroupBtn = document.getElementById('add-group-btn');
    if (addGroupBtn) {
        addGroupBtn.addEventListener('click', addTargetGroup);
    }
    
    // 测试推送按钮
    const testPushBtn = document.getElementById('test-push-btn');
    if (testPushBtn) {
        testPushBtn.addEventListener('click', testWechatPush);
    }
    
    // 保存配置按钮
    const saveConfigBtn = document.getElementById('save-config-btn');
    if (saveConfigBtn) {
        saveConfigBtn.addEventListener('click', saveWechatConfig);
    }
    
    console.log('事件绑定完成');
}

// 处理微信推送开关
function handleWechatToggle(enabled) {
    console.log(`微信推送开关已${enabled ? '开启' : '关闭'}`);
    updateWechatStatus();
}

// 手动刷新
function manualRefresh() {
    console.log('手动刷新数据');
    loadTelegrams();
    loadStats();
    updateLastRefreshTime();
}

// 改变刷新间隔
function changeRefreshInterval(seconds) {
    const milliseconds = parseInt(seconds) * 1000;
    currentIntervalTime = milliseconds;
    
    // 重新启动定时器
    stopAutoRefresh();
    startAutoRefresh();
    
    console.log(`刷新间隔已更改为 ${seconds} 秒`);
}

// 启动自动刷新
function startAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
    }
    
    refreshInterval = setInterval(function() {
        console.log('自动刷新数据');
        loadTelegrams();
        loadStats();
        updateLastRefreshTime();
    }, currentIntervalTime);
    
    console.log(`自动刷新已启动，间隔: ${currentIntervalTime/1000} 秒`);
}

// 停止自动刷新
function stopAutoRefresh() {
    if (refreshInterval) {
        clearInterval(refreshInterval);
        refreshInterval = null;
        console.log('自动刷新已停止');
    }
}

// 更新最后刷新时间
function updateLastRefreshTime() {
    const now = new Date();
    const timeString = now.toLocaleString('zh-CN');
    const lastRefreshElement = document.getElementById('last-refresh');
    if (lastRefreshElement) {
        lastRefreshElement.textContent = `最后刷新: ${timeString}`;
    }
}

// 加载电报数据
function loadTelegrams() {
    console.log('开始加载电报数据');
    const container = document.getElementById('telegrams-container');
    if (!container) return;
    
    // 显示加载状态
    container.innerHTML = '<div class="loading">正在加载数据...</div>';
    
    // 获取显示数量
    const countSelect = document.getElementById('display-count');
    const limit = countSelect ? parseInt(countSelect.value) : 50;
    
    // 发送请求
    fetch(`/api/telegrams?limit=${limit}`)
        .then(response => response.json())
        .then(data => {
            displayTelegrams(data);
            updateLastRefreshTime();
        })
        .catch(error => {
            console.error('加载电报数据失败:', error);
            container.innerHTML = '<div class="error">加载数据失败，请稍后重试</div>';
        });
}

// 显示电报数据
function displayTelegrams(telegrams) {
    const container = document.getElementById('telegrams-container');
    if (!container) return;
    
    if (!telegrams || telegrams.length === 0) {
        container.innerHTML = '<div class="loading">暂无电报数据</div>';
        return;
    }
    
    let html = '';
    telegrams.forEach(telegram => {
        html += createTelegramItem(telegram);
    });
    
    container.innerHTML = html;
}

// 创建单个电报项的HTML
function createTelegramItem(telegram) {
    // 处理阅读数样式
    let readingClass = '';
    if (telegram.reading_num >= 100000) {
        readingClass = 'very-high';
    } else if (telegram.reading_num >= 50000) {
        readingClass = 'high';
    }
    
    // 截取内容
    let content = telegram.content || '';
    if (content.length > 200) {
        content = content.substring(0, 200) + '...';
    }
    
    return `
        <div class="telegram-item">
            <div class="telegram-header">
                <div class="telegram-time">${formatTime(telegram.time)}</div>
            </div>
            <div class="telegram-title">${escapeHtml(telegram.title || '')}</div>
            <div class="telegram-content">${escapeHtml(content)}</div>
            <div class="telegram-meta">
                <div class="reading-count ${readingClass}">阅读: ${telegram.reading_num}</div>
                <a href="${telegram.url}" target="_blank" class="view-link">查看原文 →</a>
            </div>
        </div>
    `;
}

// 格式化时间
function formatTime(timeString) {
    if (!timeString) return '';
    
    try {
        const date = new Date(timeString.replace(' ', 'T'));
        return date.toLocaleString('zh-CN');
    } catch (e) {
        return timeString;
    }
}

// HTML转义
function escapeHtml(text) {
    if (!text) return '';
    const map = {
        '&': '&amp;',
        '<': '&lt;',
        '>': '&gt;',
        '"': '&quot;',
        "'": '&#039;'
    };
    return text.replace(/[&<>"']/g, function(m) { return map[m]; });
}

// 加载统计数据
function loadStats() {
    console.log('开始加载统计数据');
    fetch('/api/stats')
        .then(response => response.json())
        .then(data => {
            updateStats(data);
        })
        .catch(error => {
            console.error('加载统计数据失败:', error);
        });
}

// 更新统计数据
function updateStats(stats) {
    console.log('更新统计数据:', stats);
    if (stats.total_count !== undefined) {
        const totalCountElement = document.getElementById('total-count');
        if (totalCountElement) {
            totalCountElement.textContent = `总电报数: ${stats.total_count}`;
        }
    }
    
    if (stats.latest_time) {
        const latestTimeElement = document.getElementById('latest-time');
        if (latestTimeElement) {
            latestTimeElement.textContent = `最新更新: ${formatTime(stats.latest_time)}`;
        }
    }
}

// 加载微信配置
function loadWechatConfig() {
    console.log('加载微信配置');
    fetch('/api/wechat_config')
        .then(response => response.json())
        .then(config => {
            currentWechatConfig = config;
            updateWechatConfigUI();
        })
        .catch(error => {
            console.error('加载微信配置失败:', error);
            showStatusMessage('加载微信配置失败: ' + error.message, 'error');
        });
}

// 更新微信配置UI
function updateWechatConfigUI() {
    if (!currentWechatConfig) return;
    
    // 更新微信推送开关
    const wechatToggle = document.getElementById('wechat-toggle');
    if (wechatToggle) {
        wechatToggle.checked = currentWechatConfig.wechat_push_enabled || false;
    }
    
    // 更新临时群组列表
    tempGroups = [...(currentWechatConfig.target_groups || [])];
    
    // 更新群组列表UI
    updateGroupsList();
    
    // 更新系统信息
    const notifierStatus = document.getElementById('notifier-status');
    if (notifierStatus) {
        notifierStatus.textContent = currentWechatConfig.notifier_available ? '可用' : '不可用';
        notifierStatus.className = currentWechatConfig.notifier_available ? 'status-available' : 'status-unavailable';
    }
    
    const systemConfigStatus = document.getElementById('system-config');
    if (systemConfigStatus) {
        systemConfigStatus.textContent = currentWechatConfig.system_wechat_enabled ? '已启用' : '已禁用';
    }
    
    // 更新微信状态显示
    updateWechatStatus();
}

// 添加目标群组
function addTargetGroup() {
    const groupInput = document.getElementById('group-input');
    if (!groupInput) return;
    
    const groupName = groupInput.value.trim();
    if (!groupName) {
        showStatusMessage('请输入有效的群组名称', 'warning');
        return;
    }
    
    if (tempGroups.includes(groupName)) {
        showStatusMessage('该群组已在列表中', 'warning');
        return;
    }
    
    tempGroups.push(groupName);
    updateGroupsList();
    groupInput.value = '';
    showStatusMessage(`已添加群组: ${groupName}`, 'success');
}

// 移除目标群组
function removeTargetGroup(groupName) {
    const index = tempGroups.indexOf(groupName);
    if (index !== -1) {
        tempGroups.splice(index, 1);
        updateGroupsList();
        showStatusMessage(`已移除群组: ${groupName}`, 'success');
    }
}

// 更新群组列表UI
function updateGroupsList() {
    const groupsUl = document.getElementById('groups-ul');
    if (!groupsUl) return;
    
    if (tempGroups.length === 0) {
        groupsUl.innerHTML = '<li class="no-groups">暂无群组</li>';
        return;
    }
    
    let html = '';
    tempGroups.forEach(group => {
        html += `
            <li class="group-item">
                <span class="group-name">${escapeHtml(group)}</span>
                <button class="remove-group-btn" data-group="${escapeHtml(group)}">移除</button>
            </li>
        `;
    });
    
    groupsUl.innerHTML = html;
    
    // 绑定移除按钮事件
    document.querySelectorAll('.remove-group-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            const groupName = this.getAttribute('data-group');
            removeTargetGroup(groupName);
        });
    });
}

// 更新微信状态显示
function updateWechatStatus() {
    const wechatToggle = document.getElementById('wechat-toggle');
    const wechatStatus = document.getElementById('wechat-status');
    if (!wechatToggle || !wechatStatus) return;
    
    const status = wechatToggle.checked ? '已启用' : '已禁用';
    const statusClass = wechatToggle.checked ? 'status-enabled' : 'status-disabled';
    
    wechatStatus.textContent = `微信推送: ${status}`;
    wechatStatus.className = statusClass;
}

// 保存微信配置
function saveWechatConfig() {
    const wechatToggle = document.getElementById('wechat-toggle');
    if (!wechatToggle) return;
    
    const configData = {
        wechat_push_enabled: wechatToggle.checked,
        target_groups: tempGroups
    };
    
    console.log('保存微信配置:', configData);
    
    fetch('/api/wechat_config', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify(configData)
    })
    .then(response => response.json())
    .then(result => {
        if (result.success) {
            currentWechatConfig = result.config;
            showStatusMessage('微信配置已成功保存', 'success');
            updateWechatStatus();
        } else if (result.error) {
            showStatusMessage('保存失败: ' + result.error, 'error');
        }
    })
    .catch(error => {
        console.error('保存微信配置失败:', error);
        showStatusMessage('保存配置失败: ' + error.message, 'error');
    });
}

// 测试微信推送
function testWechatPush() {
    if (!currentWechatConfig || !currentWechatConfig.notifier_available) {
        showStatusMessage('微信推送模块不可用，无法进行测试', 'error');
        return;
    }
    
    if (tempGroups.length === 0) {
        showStatusMessage('请至少添加一个推送群组', 'warning');
        return;
    }
    
    console.log('发送测试推送');
    
    // 先显示加载状态
    const statusElement = document.getElementById('config-status');
    if (statusElement) {
        statusElement.innerHTML = '<div class="loading">正在发送测试消息...</div>';
        statusElement.className = 'status-message sending';
    }
    
    fetch('/api/wechat_push/test', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(result => {
        let message = '';
        let statusType = 'success';
        
        if (result.success) {
            message = '测试消息发送成功！';
        } else if (result.results) {
            // 有详细的结果信息
            const successResults = result.results.filter(r => r.success);
            const failResults = result.results.filter(r => !r.success);
            
            if (successResults.length > 0) {
                message += `成功发送到 ${successResults.length} 个群组:\n`;
                successResults.forEach(r => {
                    message += `- ${r.group}: ${r.message}\n`;
                });
            }
            
            if (failResults.length > 0) {
                message += `发送失败 ${failResults.length} 个群组:\n`;
                failResults.forEach(r => {
                    message += `- ${r.group}: ${r.message}\n`;
                });
                statusType = 'warning';
            }
        } else if (result.error) {
            message = '测试失败: ' + result.error;
            statusType = 'error';
        }
        
        showStatusMessage(message, statusType);
    })
    .catch(error => {
        console.error('测试微信推送失败:', error);
        showStatusMessage('测试失败: ' + error.message, 'error');
    });
}

// 显示状态消息
function showStatusMessage(message, type = 'info') {
    const statusElement = document.getElementById('config-status');
    if (!statusElement) return;
    
    // 处理多行消息
    const formattedMessage = message.replace(/\n/g, '<br>');
    
    // 设置消息内容和样式
    statusElement.innerHTML = formattedMessage;
    statusElement.className = `status-message ${type}`;
    
    // 3秒后自动隐藏成功和信息消息
    if (type === 'success' || type === 'info') {
        setTimeout(() => {
            if (statusElement) {
                statusElement.innerHTML = '';
                statusElement.className = 'status-message';
            }
        }, 3000);
    }
}

// 切换微信推送配置面板
function toggleWechatPanel(show) {
    const wechatControls = document.querySelector('.wechat-controls');
    if (!wechatControls) return;
    
    if (show === undefined) {
        // 如果没有指定是否显示，则切换当前状态
        wechatControls.classList.toggle('collapsed');
    } else if (show) {
        // 显示面板
        wechatControls.classList.remove('collapsed');
    } else {
        // 隐藏面板
        wechatControls.classList.add('collapsed');
    }
}

// 页面卸载时清理
window.addEventListener('beforeunload', function() {
    stopAutoRefresh();
});